package com.wdf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wdf.mapper.EmpExprMapper;
import com.wdf.mapper.EmpMapper;
import com.wdf.pojo.Emp;
import com.wdf.pojo.EmpExpr;
import com.wdf.pojo.OperationLog;
import com.wdf.pojo.PageResult;
import com.wdf.pojo.query.EmpQuery;
import com.wdf.service.EmpService;
import com.wdf.service.OperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private OperationLogService logService;

    @Override
    public PageResult pageList(Integer page, Integer pageSize) {
        Long total = empMapper.count();
        Integer start = (page - 1) * pageSize;
        log.info("start:{},page:{},pagesize:{}",start,page,pageSize);
        List<Emp> empList = empMapper.empPageList(start,pageSize);

        return new PageResult(total,empList);
    }

    @Override
    public PageInfo<Emp> list(EmpQuery empQuery){
        PageHelper.startPage(empQuery.getPageNum(),empQuery.getPageSize());
        List<Emp> empList = empMapper.empList(empQuery);
        return new PageInfo<>(empList);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void addEmp(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            //保存基本信息
            empMapper.addEmp(emp);
            Integer empId = emp.getId();
            List<EmpExpr> exprList = emp.getExprList();
            if(!CollectionUtils.isEmpty(exprList)){
                exprList.forEach(empExpr -> empExpr.setEmpId(empId));
                empExprMapper.addEmpExpr(exprList);
            }
        }finally {
            OperationLog operationLog = new OperationLog(null, LocalDateTime.now(), emp.toString());
            logService.insertLog(operationLog);
        }

    }
}
